use crate::models::categories::{self};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use loco_rs::prelude::*;
use crate::models::_entities::categories::CreateCategoryParams;

pub fn routes() -> Router<AppContext> {
    Router::new()
        .route("/categories", post(create))
        .route("/categories/:id", get(get_by_id))
        .route("/categories/:id/delete", post(delete))
        .route("/categories/by-slug/:slug", get(get_by_slug))
        .route("/categories/by-parent/:parent_id", get(get_by_parent))
        .route("/categories/by-catalog/:catalog_id", get(get_by_catalog))
}

async fn create(
    State(state): State<AppContext>,
    Json(params): Json<CreateCategoryParams>,
) -> Result<Response> {
    let category = categories::Model::create(&state.db, &params).await?;
    format::json(category)
}

async fn get_by_id(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let category = categories::Model::find_by_id(&state.db, &id).await?;
    format::json(category)
}

async fn delete(
    State(state): State<AppContext>,
    Path(id): Path<String>,
) -> Result<Response> {
    let category = categories::Model::find_by_id(&state.db, &id).await?;
    category.delete(&state.db).await?;
    format::json(())
}

async fn get_by_slug(
    State(state): State<AppContext>,
    axum::extract::Path(slug): Path<String>,
) -> Result<Response> {
    let category = categories::Model::find_by_slug(&state.db, &slug).await?;
    format::json(category)
}

async fn get_by_parent(
    State(state): State<AppContext>,
    axum::extract::Path(parent_id): axum::extract::Path<String>,
) -> Result<Response> {
    let categories = categories::Model::find_by_parent_id(&state.db, &parent_id).await?;
    format::json(categories)
}

async fn get_by_catalog(
    State(state): State<AppContext>,
    axum::extract::Path(catalog_id): Path<String>,
) -> Result<Response> {
    let categories = categories::Model::find_by_id(&state.db, &catalog_id).await?;
    format::json(categories)
}
